use std::{fs, sync::Arc};

use anyhow::Error;
use log::info;
use yang2::context::{Context, ContextFlags};

pub fn load_context() -> Result<Arc<Context>, Error> {
    const YANG_DIR: &str = "./yang";
    let mut ctx = Context::new(ContextFlags::ALL_IMPLEMENTED)?;
    ctx.set_searchdir(YANG_DIR)?;
    let dir = fs::read_dir(YANG_DIR)?;
    for entry in dir {
        let e = entry?;
        if let Some(name) = e.file_name().to_str() {
            if name.ends_with(".yang") {
                let file_name = name.strip_suffix(".yang").unwrap_or_default();
                let mut file_name_entry = file_name.split('@');
                let module_name = file_name_entry.next().unwrap_or_default().to_string();
                let module_version = file_name_entry.next().map(|v| v.to_string());
                ctx.load_module(&module_name, module_version.as_deref(), &["*"])?;
                info!("[loading module]: {}", name);
            }
        }
    }
    Ok(Arc::new(ctx))
}
